package org.xx.armory.swing.components.formatters;

import org.xx.armory.objectparser.ParserException;

import javax.swing.text.DefaultFormatter;
import java.text.ParseException;
import java.util.Date;

import static org.xx.armory.swing.components.FormatUtils.getDateFormat;

/**
 * 日期类型格式化器。
 */
public class DateFormatter
        extends DefaultFormatter {
    public DateFormatter(
    ) {
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Object stringToValue(
            String text
    )
            throws ParseException {
        try {
            return getDateFormat().parse(text);
        } catch (ParserException ex) {
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String valueToString(
            Object value
    ) {
        if (value instanceof Date) {
            return getDateFormat().format(value);
        } else {
            return "";
        }
    }
}
